package com.ytktt.study.week9.task3.rpcfx.client;

import com.google.common.collect.Maps;
import com.ytktt.study.week9.task3.rpcfx.client.proxy.ByteBuddyRpcfxInterceptor;
import com.ytktt.study.week9.task3.rpcfx.filter.CuicuiFilter;
import com.ytktt.study.week9.task3.rpcfx.client.proxy.ByteBuddyDynamicProxy;
import com.ytktt.study.week9.task3.rpcfx.client.proxy.RpcfxDynamicProxy;
import com.ytktt.study.week9.task3.rpcfx.filter.RequestFilterChain;
import com.ytktt.study.week9.task3.rpcfx.registry.Registry;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * rpc客户端
 *
 * @author ytk
 */
@Component
public final class Rpcfx {

    private final RpcfxDynamicProxy dynamicProxy;
    private final Map<String, Object> serviceClassMap = Maps.newHashMap();

    public Rpcfx(Registry registry, RequestFilterChain filterChain) {
        ByteBuddyRpcfxInterceptor byteBuddyRpcfxInterceptor = new ByteBuddyRpcfxInterceptor(registry, filterChain);
        this.dynamicProxy = new ByteBuddyDynamicProxy(byteBuddyRpcfxInterceptor);
    }

    public <T> T create(final String serviceName) {
        Object obj = this.serviceClassMap.get(serviceName);
        if (obj == null) {
            // 0. 替换动态代理 -> 字节码生成
            Object o = this.dynamicProxy.create(serviceName);
            this.serviceClassMap.put(serviceName, o);
            return (T) o;
        }
        return (T) obj;
    }
}
